#define _CRT_SECURE_NO_WARNINGS 1

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>

typedef struct TreeNode {
   int val;
   struct TreeNode* left;
   struct TreeNode* right;
}BTNode;

int TreeSize(struct TreeNode* root)
{
    if (root == NULL)
        return 0;

    return TreeSize(root->left) + TreeSize(root->right) + 1;
}

void Insert(int* a, struct TreeNode* root, int* pi)
{
    if (root == NULL)
        return;

    a[(*pi)++] = root->val;
    Insert(a, root->left, pi);
    Insert(a, root->right, pi);

}

//int* preorderTraversal(struct TreeNode* root, int* returnSize)
//{
//    int* a = (int*)malloc(sizeof(int) * TreeSize(root));
//
//    if (root == NULL)
//        return NULL;
//
//    int i = 0;
//    Insert(a, root, &i);
//
//    *returnSize = i;
//
//    return a;
//}


int* preorderTraversal(struct TreeNode* root, int* returnSize)
{
	*returnSize = TreeSize(root);
	int* a = (int*)malloc(sizeof(int) * (*returnSize));

	if (root == NULL)
		return NULL;

	int i = 0;
	Insert(a, root, &i);

	return a;
}

BTNode* BuyNode(int x)
{
	BTNode* node = (BTNode*)malloc(sizeof(BTNode));
	if (node == NULL)
	{
		perror("malloc");
		return NULL;
	}

	node->val = x;
	node->left = NULL;
	node->right = NULL;

	return node;
}

int main()
{
	BTNode* node1 = BuyNode(1);
	BTNode* node2 = BuyNode(2);
	BTNode* node3 = BuyNode(3);
	BTNode* node4 = BuyNode(4);
	BTNode* node5 = BuyNode(5);
	BTNode* node6 = BuyNode(6);

	node1->left = node2;
	node1->right = node4;
	node2->left = node3;
	node4->left = node5;
	node4->right = node6;

	int sz = TreeSize(node1);

	int retSize = 0;
	int* ret = preorderTraversal(node1, &retSize);
	return 0;
}